#include <iostream>
#include <fstream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 12346
#define BUFFER_SIZE 1024

int main() {
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(PORT);

    bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));

    std::ofstream outfile("udp_received_file.dat", std::ios::binary);
    char buffer[BUFFER_SIZE];
    ssize_t recvlen;
    socklen_t addrlen = sizeof(addr);
    while ((recvlen = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&addr, &addrlen)) > 0) {
        outfile.write(buffer, recvlen);
    }

    outfile.close();
    close(sockfd);
    return 0;
}    